const OrderModel = require('../model/order')

const { pool } = require('../model/baseModel')

exports.add = async (req, res, next) => {
    try {
        let result = await OrderModel.add(req.user_info.id, req.fields)
        res.send({ status: 'success', msg: '订单添加成功', data: { id: result[0].insertId } })
    } catch (error) {
        await pool.query('rollback')
        console.log(error);
        next({ status: 'fail', msg: '订单添加失败' })
    }
}

exports.delete = async (req, res, next) => {
    try {
        let result = await OrderModel.delete(req.params.id, req.user_info.id)
        res.send({ status: 'success', msg: '订单删除成功', data: { affectedRows: result[0].affectedRows } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '订单删除失败' })
    }
}

exports.findById = async (req, res, next) => {
    try {
        // console.log(req.params);
        let result = await OrderModel.findById(req.params.id, req.user_info.id)
        res.send({ status: 'success', msg: '订单查找成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '订单查找失败' })
    }
}

exports.findByUid = async (req, res, next) => {
    try {
        console.log(req.query.pageIndex);
        let result = await OrderModel.findByUid(req.user_info.id, req.query.pageIndex)
        let totalCount = await pool.query('select count(*) as total from order_info where isDel=0 and uid=?', [req.user_info.id])
        let totalPage = Math.ceil(totalCount[0][0].total / 10)
        res.send({ status: 'success', msg: '订单查找成功', data: { totalPage, list: result } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '订单查找失败' })
    }
}

exports.pay = async (req, res, next) => {
    try {
        // 这里模拟一下支付，改变一下数据库中的order_status
        let result = await OrderModel.pay(req.params.id, req.user_info.id)
        res.send({ status: 'success', msg: '订单支付成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '订单支付失败' })
    }
}